from django.db import models
from django.utils import timezone

from login.models import User


# Create your models here.

class CustomerServiceChat(models.Model):
    user_id = models.ForeignKey(User,on_delete=models.CASCADE, verbose_name="用户ID")
    message_content = models.TextField(verbose_name="消息内容")
    sender_type = models.PositiveSmallIntegerField(verbose_name="发送方类型(0-司机,1-智能客服)")
    send_time = models.DateTimeField(auto_now_add=True, verbose_name="发送时间")

    class Meta:
        db_table = 'customer_service_chats'
        verbose_name = '智能客服聊天记录'


class DispatchRecord(models.Model):
    """调度记录表"""
    driver_id = models.IntegerField(verbose_name="司机ID")
    area_id = models.CharField(max_length=100, verbose_name="区域ID")
    time_category = models.CharField(max_length=20, verbose_name="时段分类")
    recommendation_score = models.FloatField(verbose_name="推荐分数")
    accepted = models.BooleanField(default=False, verbose_name="是否接受")
    executed = models.BooleanField(default=False, verbose_name="是否执行")
    revenue_generated = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, verbose_name="产生收入")
    orders_completed = models.IntegerField(default=0, verbose_name="完成订单数")
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    executed_at = models.DateTimeField(null=True, blank=True, verbose_name="执行时间")
    
    class Meta:
        db_table = 'dispatch_records'
        verbose_name = "调度记录"
        verbose_name_plural = "调度记录"
        ordering = ['-created_at']
    
    def __str__(self):
        return f"司机{self.driver_id} - 区域{self.area_id} - {'已接受' if self.accepted else '未接受'}"

class DriverPerformance(models.Model):
    """司机表现统计表"""
    driver_id = models.IntegerField(verbose_name="司机ID")
    date = models.DateField(verbose_name="统计日期")
    time_category = models.CharField(max_length=20, verbose_name="时段分类")
    total_orders = models.IntegerField(default=0, verbose_name="总订单数")
    completed_orders = models.IntegerField(default=0, verbose_name="完成订单数")
    total_revenue = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name="总收入")
    avg_order_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0, verbose_name="平均订单金额")
    active_hours = models.FloatField(default=0, verbose_name="活跃小时数")
    created_at = models.DateTimeField(default=timezone.now, verbose_name="创建时间")
    
    class Meta:
        db_table = 'driver_performance'
        verbose_name = "司机表现统计"
        verbose_name_plural = "司机表现统计"
        unique_together = ['driver_id', 'date', 'time_category']
        ordering = ['-date', '-created_at']
    
    def __str__(self):
        return f"司机{self.driver_id} - {self.date} - {self.time_category}"
